﻿using System;
using System.Collections.Generic;
using Common;
using Consul;
using Consul.AspNetCore;
using Extensions.Consul;
using Microsoft.Extensions.DependencyInjection;

namespace Extensions.Services;

public static  class AddConsul
{
 
    public static IServiceCollection AddConsulSetup(this IServiceCollection service)
    {
        ArgumentNullException.ThrowIfNull(service);
        var consulOption = Appsettings.app<ConsulOption>("Consul");
        if (consulOption==null||!consulOption.Enable)
        {
            return service;
        }
        // 注册consulclient
        service.AddConsul(options =>
        {
            options.Address = new Uri(consulOption.ConsulAddress);
        });
        // 配置健康检查对象
        var httpCheck = new AgentServiceCheck()
        {
            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(10),// 超过10秒还没能连接到服务，就开始注销本服务
            Interval = TimeSpan.FromSeconds(10),//健康检查时间
            // 要使用这个来代替localhost  因为在docker内部是访问不到外部的localhost的  智能使用这个
            HTTP = consulOption.ServiceHealthCheckAddress,// 监控检查地址
            Timeout = TimeSpan.FromSeconds(5)// 健康检查超时时间
        };
        // 注册consul服务
        service.AddConsulServiceRegistration(options =>
        {
            options.ID = $"{consulOption.ServiceName}{consulOption.ServiceId}";// 服务的id  要是唯一的
            options.Name = consulOption.ServiceName;//服务分组名
            options.Address = consulOption.ServiceIP;//服务ip  就是当前项目的ip
            options.Port = consulOption.ServicePort;//服务的端口号
            options.Checks = new[] { httpCheck };
            options.Meta = new Dictionary<string, string>() {{"Weight",consulOption.Weight>0?consulOption.Weight.ToString():"1"}};// 权重
            options.Tags = new[] { $"urlprefix-/{consulOption.ServiceName}" }; 
        });
        service.AddSingleton<IConsulServerManager, ConsulServerManager>();
        service.AddSingleton(typeof(ConsulHelper));
        return service;
    }
}